﻿using UnityEngine;
using System.Collections;

namespace AutoRoot
{
   public class OnClickEffect : MonoBehaviour
   {
      public Sprite newImageAfterClicked;
      public Sprite newPressedImage;

      public Sprite oldImage;
      public Sprite oldPressedImage;

      private ButtonState oldState;
      private ButtonState newState;
      private ButtonState currentState;

      public ButtonStateHandler oldStateHandler;
      public ButtonStateHandler newStateHandler;

      private bool actived = false;

      void Start()
      {
         oldState = new ButtonState(oldImage, oldPressedImage, oldStateHandler);
         newState = new ButtonState(newImageAfterClicked, newPressedImage, newStateHandler);
         oldState.nextState = newState;
         newState.nextState = oldState;
         currentState = oldState;
      }

      public void OnOldState()
      {
         currentState = oldState;
         GetComponent<SpriteRenderer>().sprite = currentState.originImage;
      }

      public void OnNewState()
      {
         currentState = newState;
         GetComponent<SpriteRenderer>().sprite = currentState.originImage;
      }

      void OnTouchDown(Vector3 hitPoint)
      {
         actived = true;
         GetComponent<SpriteRenderer>().sprite = currentState.touchDownImage;
      }

      void OnScreenTouchUp()
      {
         GetComponent<SpriteRenderer>().sprite = currentState.originImage;
      }

      void OnScreenTouchExit()
      {
         GetComponent<SpriteRenderer>().sprite = currentState.originImage;
      }

      void OnTouchUp(Vector3 hitPoint)
      {
         ChangeImage();
      }

      void OnTouchExit(Vector3 hitPoint)
      {
         ChangeImage();
      }

      void ChangeImage()
      {
         if (actived)
         {
            currentState = currentState.NextState();
            GetComponent<SpriteRenderer>().sprite = currentState.originImage;
            actived = false;
         }
      }
   }
}